﻿/*
  Version: MPL 1.1/GPL 2.0/LGPL 2.1
 
  The contents of this file are subject to the Mozilla Public License Version
  1.1 (the "License"); you may not use this file except in compliance with
  the License. You may obtain a copy of the License at
  http://www.mozilla.org/MPL/
  
  Software distributed under the License is distributed on an "AS IS" basis,
  WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
  for the specific language governing rights and limitations under the
  License.
  
  The Original Code is [maashaack framework].
  
  The Initial Developers of the Original Code are
  Zwetan Kjukov <zwetan@gmail.com> and Marc Alcaraz <ekameleon@gmail.com>.
  Portions created by the Initial Developers are Copyright (C) 2004-2014
  the Initial Developers. All Rights Reserved.
  
  Contributor(s):
  
  Alternatively, the contents of this file may be used under the terms of
  either the GNU General Public License Version 2 or later (the "GPL"), or
  the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
  in which case the provisions of the GPL or the LGPL are applicable instead
  of those above. If you wish to allow use of your version of this file only
  under the terms of either the GPL or the LGPL, and not to allow others to
  use your version of this file under the terms of the MPL, indicate your
  decision by deleting the provisions above and replace them with the notice
  and other provisions required by the LGPL or the GPL. If you do not delete
  the provisions above, a recipient may use your version of this file under
  the terms of any one of the MPL, the GPL or the LGPL.
 */
package molecule.render.starling.components.panes
{
    import graphics.easings.expoOut;
    import graphics.transitions.TweenTo;

    import starling.events.Event;
    import starling.events.Touch;
    import starling.events.TouchEvent;
    import starling.events.TouchPhase;

    import system.hack;
    import system.process.Action;
    import system.process.Stoppable;

    import flash.geom.Point;
    import flash.geom.Rectangle;
    
    use namespace hack ;
    
    /**
     * Manages the scrollpane.
     */
    public class ScrollPaneManager implements Stoppable
    {
        /**
         * Creates a new ScrollPaneManager instance.
         * @param target The component reference to manage.
         */
        public function ScrollPaneManager( target:ScrollPane = null )
        {
            ///////
            
            _tween.changeIt.connect( scrollChange ) ;
            _tween.finishIt.connect( scrollFinish ) ;
            _tween.stopIt.connect( scrollFinish ) ;
            
            ///////
            
            this.target = target ;
        }
        
        /**
         * The horizontal strength ratio (default 1).
         */
        public function get horizontalStrength():Number
        {
            return _horizontalStrength ;
        }
        
        /**
         * @private
         */
        public function set horizontalStrength( value:Number ):void
        {
            _horizontalStrength = value;
        }
        
        /**
         * Indicates the scroll duration when the scroll is smoothing.
         */
        public function get scrollDuration():uint
        {
            return _tween.duration ;
        }
        
        /**
         * @private
         */
        public function set scrollDuration( value:uint ):void
        {
            _tween.duration = value ;
        }
        
        /**
         * Indicates the scroll easing function when the scroll is smoothing.
         */
        public function get scrollEasing():Function
        {
            // return _tween.easing || expoOut ; // FIXME FDT bug 
            if( _tween.easing != null )
            {
                return _tween.easing ;
            }
            else
            {
                return expoOut ;
            }
        }
        
        /**
         * @private
         */
        public function set scrollEasing( func:Function ):void
        {
            _tween.easing = func ;
        }
        
        /**
         * Indicates how many pixels constitutes a touch to scroll the content with the finger or the mouse (minimum and default 10px).
         */
        public var scrollRatio:uint = 10 ;
        
        /**
         * Controls whether or not the scrolling is smoothed when scaled.
         */
        public function get smoothing():Boolean
        {
            return _smoothing ;
        }
        
        /**
         * @private
         */
        public function set smoothing( value:Boolean ):void
        {
            if( _smoothing == value )
            {
                return ;
            }
            _smoothing = value ;
            if( !_smoothing )
            {
                stop() ;
            }
        }
        
        /**
         * Determinates the target reference of the component or custom display container to build.
         */
        public function get target():ScrollPane
        {
            return _target ;
        }
        
        /**
         * @private
         */
        public function set target( target:ScrollPane ):void
        {
            if( _target )
            {
                unregisterDisplay() ;
                unregisterMouse() ;
            }
            _target = target ;
            if( _target )
            {
                registerDisplay() ;
                if( _target.stage )
                {
                    registerMouse() ;
                }
            }
        }
        
        /**
         * Indicates if the target is touching.
         */
        public function get touching():Boolean
        {
            return _touching ;
        }
        
        /**
         * The vertical strength ratio (default 1).
         */
        public function get verticalStrength():Number
        {
            return _verticalStrength ;
        }
        
        /**
         * @private
         */
        public function set verticalStrength( value:Number ):void
        {
            _verticalStrength = value;
        }
        
        /**
         * Stop the smoothing scroll.
         */
        public function stop():void
        {
            if( _tween.running )
            {
                _tween.stop() ;
            }
            _touching = false ;
            _inertiaX = _inertiaY = 0 ;
            _diffX    = _diffY = 0 ;
            _lastX    = _lastY = 0 ;
        }
        
        ///////////////
        
        /**
         * @private
         */
        protected var _currentX:Number;
        
        /**
         * @private
         */
        protected var _currentY:Number;
        
        /**
         * @private
         */
        protected var _diffX:Number;
        
        /**
         * @private
         */
        protected var _diffY:Number;
        
        /**
         * @private
         */
        protected var _horizontalStrength:Number = 1 ;
        
        /**
         * @private
         */
        protected var _verticalStrength:Number = 1 ;
        
        /**
         * @private
         */
        protected var _inertiaX:Number ;
        
        /**
         * @private
         */
        protected var _inertiaY:Number ;
        
        /**
         * @private
         */
        protected var _lastX:Number;
        
        /**
         * @private
         */
        protected var _lastY:Number;
        
        /**
         * @private
         */
        protected var _startH:Number;
        
        /**
         * @private
         */
        protected var _startV:Number;
        
        /**
         * @private
         */
        protected var _startX:Number;
        
        /**
         * @private
         */
        protected var _startY:Number;
        
        /**
         * @private
         */
        protected var _smoothing:Boolean = true ;
        
        /**
         * @private
         */
        protected var _target:ScrollPane ;
        
        /**
         * @private
         */
        protected var _touching:Boolean ;
        
        /**
         * @private
         */
        protected const _tween:TweenTo = new TweenTo( null ,  null ,  expoOut , 24 ) ;
        
        /**
         * @private
         */
        protected var _useNaturalScrolling:Boolean = true ;
        
        ///////////////
        
        /**
         * @private
         */
        protected function addedToStage( e:Event ):void
        {
            if( _target ) 
            {
                registerMouse();
            }
        }
        
        /**
         * Determines whether the specified point is contained within the bounds of the tap target. 
         * @param x The x coordinate of the point.
         * @param y The y coordinate of the point.
         * @private
         */
        protected function contains( x:int, y:int ):Boolean
        {
            const bounds:Rectangle = _target.fixArea() ;
            return ( x >= bounds.x && x <= bounds.x + bounds.width ) && ( y >= bounds.y && y <= bounds.y + bounds.height );
        }
        
        /**
         * @private 
         */
        protected function registerDisplay():void
        {
            if( _target ) 
            {
                _target.addEventListener( Event.ADDED_TO_STAGE     , addedToStage     );
                _target.addEventListener( Event.REMOVED_FROM_STAGE , removedFromStage );
            }
        }
        
        /**
         * @private 
         */
        protected function registerMouse():void
        {
            if( _target )
            {
                _target.addEventListener( TouchEvent.TOUCH , touch );
            }
        }
        
        /**
         * @private
         */
        protected function removedFromStage( e:Event ):void
        {
            unregisterMouse();
        }
        
        /**
         * @private 
         */
        protected function unregisterDisplay():void
        {
            if( _target )
            {
                _target.removeEventListener( Event.ADDED_TO_STAGE     , addedToStage     ) ;
                _target.removeEventListener( Event.REMOVED_FROM_STAGE , removedFromStage );
            }
        }
        
        /**
         * @private 
         */
        protected function unregisterMouse():void
        {
            if( _target )
            {
                _target.removeEventListener( TouchEvent.TOUCH , touch );
            }
        }
        
        ///////////////
        
        /**
         * Invoked when the scroll with the tween change.
         */
        protected function scrollChange( action:Action ):void
        {
            if( _target )
            {
                (_target.builder as ScrollPaneBuilder).scrollChange() ;
            }
        }
        
        /**
         * Invoked when the scroll with the tween is finished.
         */
        protected function scrollFinish( action:Action ):void
        {
            _inertiaX = 0 ;
            _inertiaY = 0 ;
            if( _target )
            {
                (_target.builder as ScrollPaneBuilder).scrollFinish() ;
            }
        }
        
        protected var _pos:Point = new Point() ;
        
        /**
         * @private
         */
        hack function touch( e:TouchEvent ):void 
        {
            if( _target && !_target.enabled )
            {
                return ;
            }
            
            var touch:Touch = e.getTouch( _target ) ;
            
            if( touch )
            {
                _pos.x = touch.globalX ;
                _pos.y = touch.globalY ;
                _target.globalToLocal( _pos , _pos ) ;
                switch( touch.phase )
                {
                    case TouchPhase.BEGAN :
                    {
                        _touching = false ;
                        _inertiaX = 0 ;
                        _inertiaY = 0 ;
                        
                        if( _tween.running )
                        {
                            _tween.stop() ;
                        }
                        
                        if( _target  )
                        {
                            if( contains( _pos.x , _pos.y ) )
                            {
                                _startH = _target.scroller.x ;
                                _startV = _target.scroller.y ;
                                
                                _lastX = _startX = _pos.x ;
                                _lastY = _startY = _pos.y ;
                                
                                (_target.builder as ScrollPaneBuilder).scrollStart() ;
                                
                                _useNaturalScrolling = (_target.style as ScrollPaneStyle).useNaturalScrolling ;
                            }
                        }
                        break ;
                    }
                    case TouchPhase.ENDED :
                    {
                        if( _target )
                        {
                            if( _touching && _target.content )
                            {
                                if( _smoothing )
                                {
                                    _inertiaX = _diffX ;
                                    _inertiaY = _diffY ;
                                    
                                    if( _inertiaX != 0 || _inertiaY != 0 )
                                    {
                                        _tween.target = _target.scroller ;
                                        _tween.to     = {} ;
                                        
                                        if( _inertiaX != 0 )
                                        { 
                                            _tween.to.x = int( _target.scroller.x + ( ( _inertiaX * _horizontalStrength ) * _target.content.width  / _target.w ));
                                        } ;
                                        
                                        if( _inertiaY != 0 )
                                        { 
                                            _tween.to.y = int( _target.scroller.y + ( ( _inertiaY * _verticalStrength ) * _target.content.height / _target.h ));
                                        } ;
                                        
                                        _tween.run() ;
                                        
                                        return ;
                                    }
                                }
                            }
                            
                            //_target.mode = ScrollPane.NORMAL ;
                            (_target.builder as ScrollPaneBuilder).scrollFinish() ;
                        
                        }
                        
                        _diffX = _diffY = 0 ;
                        _lastX = _lastY = 0 ;
                        break ;
                    }
                    
                    case TouchPhase.MOVED :
                    {
                        if( _target && contains( _pos.x , _pos.y ) )
                        {
                            _currentX = _pos.x - _startX ;
                            _currentY = _pos.y - _startY ;
                            
                            _touching = (Math.abs(_currentX) > scrollRatio) || (Math.abs(_currentY) > scrollRatio) ;
                            
                            if( _touching )
                            {
                                _diffX = _useNaturalScrolling  ? int(_lastX - _pos.x)  : int(_pos.x - _lastX) ;
                                _lastX = _pos.x ;
                                
                                _diffY = _useNaturalScrolling ? int(_lastY - _pos.y) : int(_pos.y - _lastY) ;
                                _lastY = _pos.y ;
                                
                                _currentX = _useNaturalScrolling ? _startH - _currentX : _startH + _currentX ;
                                _currentY = _useNaturalScrolling ? _startV - _currentY : _startV + _currentY ; 
                                
                                (_target.builder as ScrollPaneBuilder).scrollChange( _currentX , _currentY ) ;
                            }
                        }
                        break ;
                    }
                    
                }
            }
        }
    }
}
